package task3.tracking;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import task3.tracking.service;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class TrackingActivity extends Activity {
	
	private service serviceProxy;
	private ServiceConnection serviceConnection;
	private double latitude = 60.34;
	private double longitude =43.33;
	private Button startServiceButton;
	private Button stopServiceButton;
	private Button updateButton;
	private Button exitButton;
	private TextView latTv;
	private TextView longTv;
	private TextView ratioTv;
	
	  /** boolean indicating whether the activity is bound to the service or not. */
	boolean isBound = false;
	  /**Boolean indicating whether the service has been stopped by the user. */
	boolean isStopped = false;
	
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("i", "OnCreate");
        setContentView(R.layout.main);
       // initializeService();
        longTv = (TextView)findViewById(R.id.longitude_text);
        latTv= (TextView)findViewById(R.id.latitude_text);
        ratioTv = (TextView)findViewById(R.id.ratio_text);
        startServiceButton = (Button) findViewById(R.id.start_service_button);
        startServiceButton.setOnClickListener(startServiceButtonListener);
        stopServiceButton = (Button) findViewById(R.id.stop_service_button);
        stopServiceButton.setOnClickListener(stopServiceButtonListener);
        updateButton = (Button) findViewById(R.id.update_values_button);
        updateButton.setOnClickListener(updateButtonListener);
        exitButton = (Button) findViewById(R.id.exit_button);
        exitButton.setOnClickListener(exitButtonListener);
        latTv.setText("update service");
        
    }
    
	 /** Called to initialize the underlying service */
    private void initializeService(){
    	Intent intent = new Intent();
    	intent.setClassName("task3.tracking", "task3.tracking.TrackingService");
    	serviceConnection = new TrackingServiceConnection();
    	bindService(intent,serviceConnection,Context.BIND_AUTO_CREATE);
    	
    	if(serviceProxy == null){
    		isBound = true;
    		
    	}
    	
    }
    
//    private void invokeService(){
//    	latTv.setText("invoking");
//    	if(serviceProxy == null){
//
//    		latTv.setText("Service not ready");
//    		longTv.setText("Service not ready");
//    	}
//    	else{
//    		// Variable indicating whether a binding exists to the service or not
//    		isBound = true;
//    		latTv.setText("bound");
//    		try {
//				serviceProxy.sendInitialPosToServer();
//			} catch (RemoteException e1) {
//				e1.printStackTrace();
//			}
//    	}
//
//    }
    
    private void stopService(){
//      The "Stop Service" in the activity now retrieves the latest GPS coordinates. 
//      The GPX file will be automatically updated. This means that the last coordinates in the GPX 
//      file should be used for comparison with the results of the linear dead reckoning algorithm.
    
    	if(isBound){
			unbindService(serviceConnection);

	    	latTv.setText("");
	    	longTv.setText("");
			isBound = false;
			isStopped = true;
			
			Intent svc = new Intent(this,TrackingService.class);
			stopService(svc);
			}
    }
    
    private OnClickListener startServiceButtonListener = new OnClickListener() {
    	  
    	public void onClick(View v){
 		initializeService();
 // 	    If the service already have been running, but have been stopped - initialize the service again.
//    		If not, simply invoke the service.
//    		if(isStopped){
//    			latTv.setText("Its stopped");
//    			initializeService();
//    			isStopped = false;
//    		}
//    		
//    		if(!isBound){
//    			latTv.setText("Not bound");
//				longTv.setText("Not bound");    		
//			}
//    		else if(isStopped){
//    			latTv.setText("Its stopped");
//				longTv.setText("Its stopped");  
//    		}
//    		else{
//    			try {
//    				double[] position = serviceProxy.updateLocation();
//    				latTv.setText(""+position[0]);
//    				longTv.setText(""+position[1]);
//    			} 
//    			catch (RemoteException e) {
//    				e.printStackTrace();
//    			}
//    		}
   	}
    };
    
    private OnClickListener updateButtonListener = new OnClickListener() {
    	public void onClick(View v){
    		
    		if(!isBound){
    			latTv.setText("Not bound");
				longTv.setText("Not bound");    
				ratioTv.setText("Not bound");
			}
    		else if(isStopped){
    			latTv.setText("Its stopped");
				longTv.setText("Its stopped");  
    		}
    		else{
    			try {
    				double[] position = serviceProxy.updateLocation();
    				latTv.setText(""+position[0]);
    				longTv.setText(""+position[1]);
    				ratioTv.setText(""+serviceProxy.getReductionRatio());
    			} 
    			catch (RemoteException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    };
    
  private OnClickListener stopServiceButtonListener = new OnClickListener() {
    	
    	public void onClick(View v){
    		latTv.setText("");
	    	longTv.setText("");
	    	
	    	//TODO: Send a signal to the server, so that the server can close the GPX file
	    	// for this user.
	    	stopService();
    	}
    };
    
    private OnClickListener exitButtonListener = new OnClickListener() {
    	public void onClick(View v){
    		finish();
       	}
    };
    
    class TrackingServiceConnection implements ServiceConnection
    {
		public void onServiceConnected(ComponentName arg0, IBinder boundService) {
			serviceProxy = service.Stub.asInterface(boundService);
		}

		public void onServiceDisconnected(ComponentName arg0) {
			serviceProxy = null;
		}
    };
}